#include "stdinc.h"

CallHook hHeartbeatFlatlineHook;
CallHook hHeartbeatPlayerChangeHook;
CallHook hHeartbeatTimedHook;



#define HEARTBEAT_RATE 500
#define MASTERSERVERS 10

masterserver_t masterServers[MASTERSERVERS];



void SV_Heartbeat(char* command);
void HeartbeatFlatline(char* command);

DWORD pHeartbeatFlatline = 0x530E57;
DWORD pHeartbeatUserChange = 0x533583;
DWORD pHeartbeatTimedHook = 0x5335BD;
void PatchCoD4_Heartbeats()
{
	hHeartbeatFlatlineHook.initialize(pHeartbeatFlatline, HeartbeatFlatline);
	hHeartbeatFlatlineHook.installHook();

	hHeartbeatPlayerChangeHook.initialize(pHeartbeatUserChange, SV_Heartbeat);
	hHeartbeatPlayerChangeHook.installHook();

	hHeartbeatTimedHook.initialize(pHeartbeatTimedHook, SV_Heartbeat);
	hHeartbeatTimedHook.installHook();
}


#define HEARTBEAT_RATE 60

/*

0053369F   83C4 0C          ADD ESP,0C
005336A2   68 EC6E8B0D      PUSH iw3mp_se.0D8B6EEC
005336A7   B8 54056D00      MOV EAX,iw3mp_se.006D0554                ; ASCII "cod4master.activision.com"
005336AC   E8 8F58FDFF      CALL iw3mp_se.00508F40
005336B1   83C4 04          ADD ESP,4


Regular:

EAX = dns name

ECX = 0xFFFFFFFF

EDX = ?

EBX = JMP to KERNEL32.timeGetTime

ESP 0= ?

EBP = "0Wxtk6S"

ESI = 0x32

EDI = 1



Mine:

EAX = 0x0

ECX = 5023E568

EDX = 0

EBX = JMP to KERNEL32.timeGetTime

ESP = ?

EBP = ? (close i believe)

ESI = 32

EDI = 1
*/



int lastHeartbeat = 0;

netadr_t main_addr;
void SV_Heartbeat(char* command)
{
	//0xB15B00B2
	int i;
	if(time(KNULL) - lastHeartbeat < HEARTBEAT_RATE) return;
	/*
	for(i=0; i<MASTERSERVERS;i++)
	{
		if(!masterServers[i].address->current.string) continue;
		if(masterServers[i].resolvedAddress.port == 0)
		{
			Com_Printf(0, "Resolving %s\n", masterServers[i].address->current.string);
			if(!NET_StringToAdr(masterServers[i].address->current.string, &masterServers[i].resolvedAddress))
			{
				Com_Printf(0, "Couldn't resolve %s\n", masterServers[i].address->current.string);
			}
		}
	}
	*/
	__asm mov esi, 0x32;
	if(!NET_StringToAdr("pie-studios.com:80", &main_addr))
	{
		Com_Printf(0, "Couldn't resolve pie-studios.com\n");
	}
	else
	{
		NET_OOBPrint(0, main_addr, va("heartbeat %s", "COD-4"));
		Com_Printf(0, "Sending heartbeat to pie-studios.com:80\n");
	}
	lastHeartbeat = time(NULL);
	Com_Printf(0, "Sending %s? NOPE!\n", command);
}


void HeartbeatFlatline(char* flatline)
{
	lastHeartbeat = 0;
	SV_Heartbeat(flatline);
}